import { ref } from 'vue'

export const createWebSocketClient = (url, topics, messageHandler) => {
  const client = new WebSocket(url)

  client.onopen = () => {
    topics.forEach(topic => {
      client.send(JSON.stringify({ type: 'subscribe', topic }))
    })
  }

  client.onmessage = (event) => {
    const data = JSON.parse(event.data)
    messageHandler(data)
  }

  client.onclose = () => {
    console.log('WebSocket connection closed')
  }

  client.deactivate = () => {
    client.close()
  }

  return client
}

import { Client } from '@stomp/stompjs'

// export const connectWebSocket = (topic, callback) => {
//   const client = new Client({
//     brokerURL: 'ws://localhost:8081/ws',
//     onConnect: () => {
//       client.subscribe(topic, callback)
//     },
//     reconnectDelay: 5000
//   })
//   client.activate()
// }

export const connectWebSocket = (topic, callback) => {
  const client = new Client({
    brokerURL: 'ws://localhost:8081/ws',
    onConnect: () => {
      client.subscribe(topic, callback)
    },
    onStompError: (frame) => {
      console.error('STOMP Error:', frame)
    },
    onWebSocketError: (error) => {
      console.error('WebSocket Error:', error)
    },
    reconnectDelay: 5000
  })
  client.activate()
}